package com.mohunhun.controller;

import com.mohunhun.common.AppResult;
import com.mohunhun.common.ResultCode;
import com.mohunhun.config.AppConfig;
import com.mohunhun.model.Article;
import com.mohunhun.model.Board;
import com.mohunhun.model.User;
import com.mohunhun.services.IArticleService;
import com.mohunhun.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Tag(name = "帖子接口")
@RestController
@RequestMapping("/article")
public class ArticleController {


    @Resource
    private IBoardService boardService;

    @Resource
    private IArticleService articleService;


    @Operation(summary = "发帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Parameter(description = "板块id") @RequestParam("boardId") @NonNull Long boardId,
                            @Parameter(description = "文章标题") @RequestParam("title") @NonNull String title,
                            @Parameter(description = "帖子内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }


        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);

        articleService.create(article);


        return AppResult.success();
    }


    @Operation(summary = "根据Id查询帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@Parameter(description = "板块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> result = null;

        if (boardId == null) {
            result = articleService.selectAll();
        } else {
            result = articleService.selectAllByBoardId(boardId);
        }

        if (result == null) result = new ArrayList<>();


        return AppResult.success(result);
    }


    @GetMapping("/getById")
    @Operation(summary = "根据Id获取详情")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);


        Article article = articleService.selectDetailById(id);
        if (article == null) return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);

        if (user.getId() == article.getUserId() || user.getIsAdmin() == 1) {
            article.setIsOwn(true);
        }

        return AppResult.success(article);
    }

    @Operation(summary = "修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id,
                            @Parameter(description = "帖子标题") @RequestParam("title") @NonNull String title,
                            @Parameter(description = "帖子正文") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if (article.getUserId() != user.getId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }


        articleService.modify(id, title, content);

        log.info("帖子更新成功. Article id" + id + ",User id=" + user.getId() + "。");

        return AppResult.success();
    }


    @Operation(summary = "点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }


        articleService.thumbsUpById(id);
        log.info("帖子点赞成功. Article id" + id + ",User id=" + user.getId() + "。");

        return AppResult.success();
    }


    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(
            HttpServletRequest request,
            @Parameter(description = "帖子id")
            @RequestParam("id")
            @NonNull Long id) {

        HttpSession session = request.getSession(false);


        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 本人可以删除，管理员也可以删除
        if (user.getId().equals(article.getUserId()) || user.getIsAdmin() == 1) {
            articleService.deleteById(id);
            log.info("用户 {} 删除帖子 {} 成功", user.getId(), id);
            return AppResult.success();
        } else {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
    }

    @Operation(summary = "获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @Parameter(description = "用户id") @RequestParam(value = "userId", required = false) Long userId) {
        if (userId == null) {
            User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        return AppResult.success(articleService.selectByUserID(userId));
    }

}
